package l1j.server;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * 登入資料庫連接設置管理
 */
public class DatabaseFactoryLogin {

	private static final Logger _log = Logger.getLogger(DatabaseFactoryLogin.class.getName() );

	private static DatabaseFactoryLogin _instance;

	// 連接池
	private ComboPooledDataSource _source;

	// 驅動程式
	private static String _driver;

	// 資料庫位置
	private static String _url;

	// 使用者名稱
	private static String _user;

	// 使用者密碼
	private static String _password;

	/**
	 *
	 * @return
	 * @throws SQLException
	 */
	public static DatabaseFactoryLogin get() throws SQLException {
		if (_instance == null) {
			_instance = new DatabaseFactoryLogin();
		}
		return _instance;
	}

	/**
	 * 初始化設置
	 *
	 * @param driver 驅動程式
	 * @param url 資料庫位置
	 * @param user 使用者名稱
	 * @param password 使用者密碼
	 */
	public static void setDatabaseSettings() {
		//(Config.DB_DRIVER, Config.DB_URL,Config.DB_LOGIN, Config.DB_PASSWORD);
		_driver = Config.DB_DRIVER;
		_url = Config.DB_URL;
		_user = Config.DB_LOGIN;
		_password = Config.DB_PASSWORD;
	}

	/**
	 * 設置資料載入
	 *
	 * @throws SQLException
	 */
	public DatabaseFactoryLogin() throws SQLException {
		try {
			this._source = new ComboPooledDataSource();
			this._source.setDriverClass(_driver);
			this._source.setJdbcUrl(_url);
			this._source.setUser(_user);
			this._source.setPassword(_password);

			this._source.getConnection().close();

		} catch (final SQLException e) {
			_log.log(Level.SEVERE,"資料庫讀取錯誤!", e);

		} catch (final Exception e) {
			_log.log(Level.SEVERE ,"資料庫讀取錯誤!", e);

		}
	}

	/**
	 * 傳回資料庫連接
	 *
	 * @return Connection
	 * @throws SQLException
	 */
	public Connection getConnection() {
		Connection con = null;

		while (con == null) {
			try {
				con = this._source.getConnection();

			} catch (final SQLException e) {
				_log.log(Level.SEVERE ,e.getLocalizedMessage(), e);
			}
		}
		return con;
	}

	/**
	 * 資料庫連線關閉
	 */
	public void shutdown() {
		try {
			this._source.close();

		} catch (final Exception e) {
			_log.log(Level.SEVERE ,e.getLocalizedMessage(), e);
		}
		try {
			this._source = null;

		} catch (final Exception e) {
			_log.log(Level.SEVERE ,e.getLocalizedMessage(), e);
		}
	}
}
